﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;


namespace Grinko.Serializator
{
    /// <summary>
    /// JSONSerializer for JSONObject
    /// </summary>
    public class JSONSerializer:IAssignable
    {
        #region Assign implementation

        public string AssignTo(object obj)
        {
            string str = null;

            if (obj == null)
                throw new ArgumentNullException();

            if (obj != null)
            {
                Type myType = obj.GetType();
                str = "{type:" + myType.Name;
                if (myType.IsArray)
                {
                    Array myArray = (Array)obj;
                    for (int i = 0; i < myArray.Length; i++)
                    {
                        str = str + ",\n";
                        str = str + "[" + Convert.ToString(i) + "]:";
                        str = str + Convert.ToString(myArray.GetValue(i));
                    }
                    str = str + "\n}";
                }
                else
                {
                    if (myType.IsClass)
                    {
                    PropertyInfo[] myPropertyInfo = myType.GetProperties();
                      foreach (PropertyInfo pr in myPropertyInfo)
                        {
                            if ((!pr.PropertyType.IsValueType) & (pr.PropertyType != typeof(string)))
                            {
                                throw new NotSupportedException();
                            }
                            else
                            {
                                str = str + ",\n";
                                str = str + pr.Name + ":";
                                str = str + pr.GetValue(obj, null).ToString();
                            }
                        }
                        str = str + "\n}";
                    }
                }
            }
            return str;
        }

        #endregion
    }
}
